package com.frxuexi.mymvi

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.frxuexi.base.http.ApiService
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class MviViewModel  @Inject constructor(val apiService: ApiService):ViewModel(){
    val channel = Channel<MviIntent>()

    private var _uiState= MutableStateFlow<MviState>(MviState.onLoading)
    val uiState:StateFlow<MviState>
        get() = _uiState

    init {
        viewModelScope.launch {
            channel.receiveAsFlow().collect{
                 when(it){
                    is MviIntent.getApps->{
                        getApp()
                    }
                     else -> {}
                 }
            }
        }

    }

    fun getApp(){
        viewModelScope.launch {
            apiService.getApps().flowOn(Dispatchers.IO)
                .catch {
                    Log.i("lr",it.message.toString())
                }.collect{
                    if(it.code==0){
                        _uiState.value=MviState.onSuccess(it.data)
                    }else{
                        _uiState.value=MviState.onError(it.msg)
                    }
                }

        }
    }
}